package tongwentongshu.com.app.presenter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.AoiItem;
import com.amap.api.services.geocoder.BusinessArea;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.BookTypeBean;
import tongwentongshu.com.app.bean.OrderEvent;
import tongwentongshu.com.app.bean.PioBean;
import tongwentongshu.com.app.bean.ShareBean;
import tongwentongshu.com.app.contract.ShareBookContract;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.map.ClusterControl;
import tongwentongshu.com.app.map.LocationOnSuccess;
import tongwentongshu.com.app.map.MapLocation;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.update.UpdateFractory;
import tongwentongshu.com.app.utils.FileUtil;
import tongwentongshu.com.app.utils.ToastUtil;

import static tongwentongshu.com.app.App.CODE;
import static tongwentongshu.com.app.App.NAME;
import static tongwentongshu.com.app.App.POINT;

/**
 * Created by XiongBin on 2017/6/27.
 */

public class ShareBookPresenter implements ShareBookContract.Presenter, GeocodeSearch.OnGeocodeSearchListener {
    ShareBookContract.View sharebook;
    private Map<String, String> map;
    private Map<String, String> mapType;
    private MapLocation mapLocation;//定位对象
    private Context mContext;
    //逆地理编码查询
    private GeocodeSearch geocoderSearch;


    public ShareBookPresenter(ShareBookContract.View sharebook) {
        this.sharebook = sharebook;
    }

    @Override
    public void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 1) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 2);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    editText.setText("");
                    editText.setSelection(0);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() < 2) {
                    editText.setText("");
                    editText.setSelection(0);
                    return;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }

    @Override
    public void getAddress(Activity act) {
        mContext = act;
        mapLocation = new MapLocation(act);
        mapLocation.toLocation(locationOnSuccess);
    }

    @Override
    public List<PoiItem> getPoiList() {
        return list;
    }

    /**
     * 得到类别
     */
    @Override
    public void getBookType() {
//        AlertUtils.showLoding(mContext);
        mapType = new ArrayMap<>();
        UpdateFractory.getBuild()
                .name("BookTypeListCall")
                .map(mapType)
                .build()
                .execute(new ResponseSubscriber<BookTypeBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
//                        AlertUtils.disMissLoding();
                    }

                    @Override
                    public void onSuccess(BookTypeBean appItem, String msg) {
                        sharebook.setBookType(appItem);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
//                        AlertUtils.disMissLoding();
                    }
                });
    }

    /**
     * 提交接口
     */
    @Override
    public void share() {

//        map = new ArrayMap<>();
        UpdateFractory.getBuild()
                .name("ReleaseBookCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<ShareBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        AlertUtils.disMissLoding();
                    }

                    @Override
                    public void onSuccess(ShareBean appItem, String msg) {
                        map.clear();
                        sharebook.shareOnSuccess(appItem);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        AlertUtils.disMissLoding();
                    }
                });
    }

    @Override
    public Map<String, String> getStreet() {
        Map<String, String> map = new HashMap<String, String>();
        if (result.getRegeocodeAddress().getBusinessAreas().size() > 0) {
            BusinessArea b = result.getRegeocodeAddress().getBusinessAreas().get(0);
            map.put(NAME, b.getName());
            map.put(POINT, b.getCenterPoint().getLongitude() + "," + b.getCenterPoint().getLatitude());
            return map;
        } else {
            return getTradingarea();
        }

    }

    @Override
    public Map<String, String> getTradingarea() {
        Map<String, String> map = new HashMap<String, String>();
        if (result.getRegeocodeAddress().getAois().size() > 0) {
            AoiItem a = result.getRegeocodeAddress().getAois().get(0);
            map.put(NAME, a.getAoiName());
            map.put(CODE, a.getAoiId());
            map.put(POINT, a.getAoiCenterPoint().getLongitude() + "," + a.getAoiCenterPoint().getLatitude());
            return map;
        } else {
            PoiItem p = result.getRegeocodeAddress().getPois().get(0);
            map.put(NAME, p.getTitle());
            map.put(CODE, p.getPoiId());
            map.put(POINT, p.getLatLonPoint().getLongitude() + "," + p.getLatLonPoint().getLatitude());
            return map;
        }
    }

    String cover_url;
    String cover_back_url;

    /**
     * 提交
     *
     * @param url1
     * @param url2
     */
    @Override
    public void Submit(Map<String, String> map, String url1, String url2) {
        cover_url = url1;
        cover_back_url = url2;
        this.map = map;

        if (!TextUtils.isEmpty(cover_url)) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            /**
             * 最关键在此，把options.inJustDecodeBounds = true;
             * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
             */
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(cover_url, options); // 此时返回的bitmap为null
            /**
             *options.outHeight为原始图片的高
             */
            Log.e("Test", "Bitmap Height == " + options.outHeight);
            map.put("headwidth", String.valueOf(options.outWidth));
            map.put("headheigh", String.valueOf(options.outHeight));
        }
        if (!TextUtils.isEmpty(cover_back_url)) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            /**
             * 最关键在此，把options.inJustDecodeBounds = true;
             * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
             */
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(cover_back_url, options); // 此时返回的bitmap为null
            /**
             *options.outHeight为原始图片的高
             */
            Log.e("Test", "Bitmap Height == " + options.outHeight);
            map.put("footwidth", String.valueOf(options.outWidth));
            map.put("footheigh", String.valueOf(options.outHeight));
        }
        initThreadHandler();
        mMarkerhandler.sendEmptyMessage(MarkerHandler.HANDLE_COVER);
    }

    //初始化Handler
    private void initThreadHandler() {
        mMarkerHandlerThread.start();
        mMarkerhandler = new MarkerHandler(mMarkerHandlerThread.getLooper());
    }

    private AMapLocation location;

    public AMapLocation getAMapLocation() {
        return location;
    }

    //定位完毕回调
    public LocationOnSuccess locationOnSuccess = new LocationOnSuccess() {
        @Override
        public void onLocation(AMapLocation location) {
            if (null != location) {
                ShareBookPresenter.this.location = location;
                geocoderSearch = new GeocodeSearch(mContext);
                geocoderSearch.setOnGeocodeSearchListener(ShareBookPresenter.this);
                RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(location.getLatitude(), location.getLongitude()), 3000,
                        GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
            }

        }
    };
    private List<PoiItem> list;
    private RegeocodeResult result;

    public RegeocodeResult getRegeocodeResult() {
        return result;
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                Log.e("onRegeocodeSearched", result.getRegeocodeAddress().getBusinessAreas().get(0).getName());
                ShareBookPresenter.this.result = result;
                list = result.getRegeocodeAddress().getPois();
                sharebook.setLocation(list.get(0).getTitle());
                sharebook.setPoiItem(list.get(0));
//
            } else {
                ToastUtil.show(mContext, "无");
            }
        } else {
            ToastUtil.showerror(mContext, rCode);
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    private HandlerThread mMarkerHandlerThread = new HandlerThread("Handle_img");//添加marker的线程
    private Handler mMarkerhandler;

    /**
     * 处理图片提交
     */
    public class MarkerHandler extends Handler {

        static final int HANDLE_COVER = 1;//处理封面
        static final int HANDLE_BACK_COVER = 2;//处理底面
        static final int SUBMIT = 3;//提交

        MarkerHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message message) {

            switch (message.what) {
                case HANDLE_COVER:
                    if (!TextUtils.isEmpty(cover_url)) {
                        String base64_cover = FileUtil.bitmapToString(cover_url);
                        map.put("imagehead", base64_cover);
                    }
                    mMarkerhandler.sendEmptyMessage(MarkerHandler.HANDLE_BACK_COVER);
                    break;
                case HANDLE_BACK_COVER:
                    if (!TextUtils.isEmpty(cover_back_url)) {
                        String base64_cover = FileUtil.bitmapToString(cover_back_url);
                        map.put("imagefoot", base64_cover);
                    }
                    mMarkerhandler.sendEmptyMessage(MarkerHandler.SUBMIT);
                    break;
                case SUBMIT:
                    share();
                    break;
            }
        }
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param url
     * @return
     */
    public String Bitmap2StrByBase64(String url) {
        Bitmap bit = getLoacalBitmap(url);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 加载本地图片
     * from Internet
     *
     * @param url
     * @return
     */
    public Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


}
